import uuid

from django.contrib.auth.hashers import make_password
from django.core.cache import cache
from django.core.mail import send_mail
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

# Create your views here.
from django.template import loader

from Userapp.models import axfUser
from Userapp.views_helper import make_email


def login(request):
    return render(request, 'axf/user/login/login.html')


def register(request):
    if request.method == 'GET':
        return render(request, 'axf/user/register/register.html')
    elif request.method == 'POST':
        # 获取注册信息
        name = request.POST.get('name')
        password = request.POST.get('password')
        email = request.POST.get('email')
        icon = request.FILES.get('icon')
        password = make_password(password)
        # 注册信息写入到数据库
        user = axfUser()
        user.name = name
        user.password = password
        user.email = email
        user.icon = icon
        # 设置token
        token = uuid.uuid4()
        user.token = token

        user.save()
         # 设置缓存
        cache.set(token,user.id,timeout=60)

        # 传到make_email方法中，渲染到激活页面
        make_email(name, email, token)
        return HttpResponse('注册成功')


def ckeckName(request):
    data = {
        'msg': '用户名可以使用',
        'status': 200
    }
    name = request.GET.get('name')
    users = axfUser.objects.filter(name=name)
    if users.exists():
        data['msg'] = '用户名不可以使用'
        data['status'] = 201
        return JsonResponse(data=data)
    else:
        return JsonResponse(data=data)


def testEmail(request):
    # host: EMAIL_HOST
    # port: EMAIL_PORT
    # username: EMAIL_HOST_USER
    # password: EMAIL_HOST_PASSWORD

    # send_mail( subject, message, from_email, recipient_list,)
    # 主题
    subject = '激活'
    # 邮件的内容
    message = '邮件来了'

    # 加载
    index = loader.get_template('axf/user/register/active.html')
    # 渲染
    context = {
        'name': '周海军',
        'url': 'http://www.my6767.com/pro_18539982.html'
    }
    # html格式的内容
    html_message = index.render(context=context)

    # 发送者
    from_email = 'zhj_150@163.com'
    # 接受者 必须为列表[]
    recipient_list = ['zhj_150@163.com']

    send_mail(subject=subject, message=message, html_message=html_message, from_email=from_email,
              recipient_list=recipient_list)

    return HttpResponse('邮件注册成功')


def account(request):
    # 获取token唯一值
    token = request.GET.get('token')

    user_id = cache.get(token)

    if user_id:
        user = axfUser.objects.get(pk=user_id)
        user.active = True
        user.save()
        # 一次激活后删除缓存
        cache.delete(token)

        return HttpResponse('激活成功')
    else:
        return HttpResponse('邮件已过期')


    # users = axfUser.objects.filter(token=token)
    #
    # if users.count() > 0:
    #     user = users.first()
    #     user.active = True
    #     user.save()
    #
    # return HttpResponse('激活成功')
